// 云函数入口文件
const cloud = require('wx-server-sdk')
const cheerio = require('cheerio') // 操作html结构
const charset = require('superagent-charset') // 解决乱码
const superagent = require('superagent') // 发接口请求
charset(superagent)
cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  let serverUrl = `https://m.biqiugege8.com/${event.url}`
  const result = await (superagent.get(serverUrl)).charset('gb2312')
  const data = result.text || ""; //防止报错
  const $ = cheerio.load(data);

  // 书籍信息
  let bookData = [];
  let bookcover = $('.book_info').find('.cover')
  let book_box = $('.book_info').find('.book_box').find('dl')
  let bookObj = {}
  bookObj['cover'] = $(bookcover).find('img').attr('src')
  bookObj['bookname'] = $(book_box).find('dt').text()
  let bookcontent = $(book_box).find('span');
  // console.log(bookcontent);
  bookObj['bookauthor'] = $(bookcontent)[0].children[0].data
  bookObj['bookclass'] = $(bookcontent)[1].children[0].data
  bookObj['booksituation'] = $(bookcontent)[2].children[0].data
  bookObj['bookcounts'] = $(bookcontent)[3].children[0].data
  bookObj['bookupdate'] = $(bookcontent)[4].children[0].data
  bookObj['booklastestTitle'] = $(bookcontent)[5].children[0].data
  bookObj['booklastestLast'] = $(bookcontent)[5].children[1].children[0].data
  bookObj['booklastestHref'] = $(bookcontent)[5].children[1].attribs.href

  //内容简介
  bookObj['about'] = $('.book_about').find('dd').text()

  //最新章节和所有章节
  let p = $('.books').find('.book_last').find('dl')[0]
  let q = $('.books').find('.book_last').find('dl')[1]
  let arrp = []
  let arrq = []
  let len = p.children.length
  let len1 = q.children.length
  let phref = $('.books').find('.book_last').first().find('a')
  for (let i = 1; i < len / 2 - 1; i++) {
    arrp.push(p.children[2 * i + 1].children[0].children[0].data) 
    arrp.push({
      'href': phref[i - 1].attribs.href,
      'section': p.children[2 * i + 1].children[0].children[0].data
    })
  }
  for (let i = 1; i < len1 / 2; i++) {
    arrq.push({
      'href': q.children[2 * i].children[0].attribs.href,
      'section': q.children[2 * i].children[0].children[0].data
    })
  }
  bookObj.sectionList = arrq
  bookObj.lastNewList = arrp
  bookData.push(bookObj)


  // 上一页和下一页地址
  let pre=$('.listpage').find('.left').find('a').attr('href')
  let next=$('.listpage').find('.right').find('a').attr('href')

  // 获取所有的分页
  let pageArray=[]
  const pageNum=$('.listpage').find('.middle').find('select').find('option')
  for(let i=0;i<pageNum.length;i++){
    let obj={}
    obj['name']=$(pageNum[i]).attr('value')
    obj['num']=i+1,
    pageArray.push(obj)
  }

  return {
    bookData,
    pre,
    next,
    pageArray
  }

}